package com.lw.extraceim.ui.activity.tp;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lw.extraceim.R;
import com.lw.extraceim.loader.ExpressSheetLoader;
import com.lw.extraceim.loader.PackageLoader;
import com.lw.extraceim.model.ExpressSheet;
import com.lw.extraceim.model.TransPackage;
import com.lw.extraceim.net.HttpResponseParam;
import com.lw.extraceim.net.ResponseCode;
import com.lw.extraceim.net.callback.HttpResponseParamCallback;
import com.lw.extraceim.ui.activity.MainActivity;
import com.lw.extraceim.ui.activity.base.BaseActivity;
import com.lw.extraceim.ui.activity.customer.CustomerListActivity;
import com.lw.extraceim.ui.adapter.ExpressSheetAdapter;
import com.lw.extraceim.util.JsonUtils;
import com.lw.extraceim.view.ExtraceToolbar;
import com.lw.extraceim.zxing.ExtraceCaptureActivity;

import org.json.JSONException;

import java.util.List;

import okhttp3.Call;

/**
 * @Author : liwei
 * @Email : 1759840027@qq.com
 * @Description :添加快件到包裹中的页面
 * @Date : 2019/5/11 9:09
 */
public class AddEsActivity extends BaseActivity {

    private static final String TAG = "AddEsActivity";

    private static final String PACKAGE_NAME = "package";

    private ListView mEsList;
    private Button mAddEs;

    private ExpressSheetAdapter esAdapter;


    //当前界面上的快件列表
    private List<ExpressSheet> expressSheetList;
    //当前界面的包裹信息
    private TransPackage transPackage;
    //加载快件
    private ExpressSheetLoader esLoader;
    //加载包裹
    private PackageLoader packageLoader;

    private  ExtraceToolbar mToolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_add_es);
        mToolbar = findViewById(R.id.toolbar);
        initToolBar();

        mEsList = findViewById(R.id.es_list);
        mAddEs = findViewById(R.id.add_es);
    }

    /**
     * 初始化toolBar
     */
    protected void initToolBar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        mToolbar.setBackButtonOnClickListerner(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AddEsActivity.this.finish();
            }
        });
        mToolbar.setButtonOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MainActivity.actionStart(AddEsActivity.this);
            }
        });
    }

    @Override
    public void initData() {
        esLoader = new ExpressSheetLoader(this);
        packageLoader = new PackageLoader(this);
        transPackage = (TransPackage) getIntent().getSerializableExtra(PACKAGE_NAME);
        Log.d(TAG, "initData: " + transPackage);
        checkTransPackage();
        loadEsList();
    }

    @Override
    public void refreshUI() {
        refreshEsList();
    }

    @Override
    public void initEvent() {
        mAddEs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQRScan(AddEsActivity.this, ExtraceCaptureActivity.class, "扫描快件", ExtraceCaptureActivity.SCAN_SEARCH);
            }
        });
    }

    /**
     * 检查包裹信息是否为空
     */
    public void checkTransPackage() {
        if (transPackage == null || transPackage.getId() == null) {
            toast("包裹信息错误");
            finish();
        }
    }

    private HttpResponseParamCallback esListCallback = new HttpResponseParamCallback() {
        @Override
        public void onError(Call call, Exception e, int id) {
            toast("网络错误" + e.getMessage());
        }

        @Override
        public void onResponse(HttpResponseParam response, int id) {
            Log.d(TAG, "onResponse: " + response.reseponseJson);
            if (response.code.getCode() == ResponseCode.SUCESS) {
                try {
                    expressSheetList = JsonUtils.fromJson(response.reseponseJson.getJSONArray("esList").toString(), new TypeToken<List<ExpressSheet>>() {
                    });
                    refreshEsList();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                toast("加载快件列表失败");
            }
        }
    };

    /**
     * 加载包裹中的快件列表
     */
    public void loadEsList() {
        esLoader.getEsList(transPackage.getId(), esListCallback);
    }

    /**
     * 更新界面上的快件信息
     */
    public void refreshEsList() {
        if (expressSheetList == null || expressSheetList.isEmpty()) {
            toast("快件信息为空");
        } else {
            if (esAdapter == null) {
                esAdapter = new ExpressSheetAdapter(expressSheetList, this);
            } else {
                esAdapter.setData(expressSheetList);
            }
        }
        mEsList.setAdapter(esAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case ExtraceCaptureActivity.SCAN_SEARCH: {
                IntentResult scanResult = IntentIntegrator.parseActivityResult(IntentIntegrator.REQUEST_CODE, resultCode, data);
                if (scanResult != null) {
                    String esId = scanResult.getContents();
                    addEsToPackage(esId);
                    toast("扫描成功");
                } else {
                    toast("扫描错误");
                }
                break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //添加快件到包裹中
    public void addEsToPackage(String esId) {
        packageLoader.moveESInToPackage(transPackage.getId(), esId, new HttpResponseParamCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                toast("网络错误" + e.getMessage());
            }

            @Override
            public void onResponse(HttpResponseParam response, int id) {
                if (response.code.getCode() == ResponseCode.SUCESS){
                    toast("添加成功");
                    showDialog("提示", "是否继续添加快件", "继续添加", "停止添加", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startQRScan(AddEsActivity.this, ExtraceCaptureActivity.class, "扫描快件", ExtraceCaptureActivity.SCAN_SEARCH);
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    loadEsList();
                }else{
                    toast("添加失败" + (response.code.getMessage() != null ?response.code.getMessage() : ""));
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        this.finish();
    }

    /**
     * 启动当前Activity
     *
     * @param context
     * @param transPackage
     */
    public static void actionStart(Activity context, TransPackage transPackage) {
        Intent intent = new Intent(context, AddEsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable(PACKAGE_NAME, transPackage);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }
}
